<template>
  <div class="ImageUpload">
    <el-upload
      action="#"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :file-list="fileList"
      :class="{disable : fileList.length > 0}"
      :on-change="handleChange"
      :http-request="uploade"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <!-- <el-progress v-if="isShow" type="circle" :percentage="percentage" /> -->
    <el-dialog :visible.sync="dialogVisible" title="预览">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDc3GD80YwgBQP8anlZiDSSCgusa2FCtRt',
  SecretKey: 'Z1y0IxObZIm2N8evx2rJLLuTpw1rFOcb'
})
export default {
  data() {
    return {
      isShow: false,
      percentage: 0,
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [
      ]
    }
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList)
      this.fileList = [...fileList]
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleChange(file, fileList) {
      this.fileList = [...fileList]
    },
    // 上传前校验
    beforeUpload(file) {
      console.log('上传前校验')
      console.log('file')
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('上传图片只能是 JPG、GIF、BMP、PNG 格式!')
        return false
      }
      const maxSize = 200 * 1024 * 1024
      if (file.size > maxSize) {
        this.$message.warning('图片大小不能超过' + maxSize / 1024 + 'K')
        return false
      }
      this.isShow = true
    },
    uploade(data) {
      console.log(data)
      cos.putObject({
        Bucket: '61209-1305637089', /* 必须 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，必须字段 */
        Key: data.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: data.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          // this.percentage = progressData.percent * 100
          data.file.percent = progressData.percent * 100
          data.onProgress(data.file)
        }
      }, (err, data) => {
        console.log(err || data)
        if (!err) {
          this.fileList[0].url = 'http://' + data.Location
          this.fileList[0].status = 'success'
        }
        setTimeout(() => {
          this.isShow = false
        }, 800)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.ImageUpload{
  ::v-deep .disable {
   .el-upload--picture-card {
    display: none;
    }
  }
  ::v-deep img{
  object-fit:cover
  }

}

</style>
